﻿using System;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using PhotoAlbums.Models;
using PhotoAlbums.Models.VO;
using System.Collections.Generic;
using System.Web;
using System.IO;

namespace PhotoAlbums.Controllers
{
    public class PhotoController : Controller
    {
        private PhotoAlbumsDB db = new PhotoAlbumsDB();

        // GET: Photo
        public ActionResult Index(int? catalogId)
        {
            // 未登录跳转
            if (Session["id"] == null)
            {
                return RedirectToAction("Login", "User");
            }

            // 判断是否为自己的目录
            List<UserCatalog> userCatalogs = db.UserCatalog.Where(u => u.CatalogId == catalogId).ToList();
            if (userCatalogs == null || userCatalogs.Count != 1 || userCatalogs[0].UserId != (int)Session["id"])
            {
                return RedirectToAction("Login", "User");
            }

            if (catalogId == null)
            {
                return RedirectToAction("Index", "Catalog");
            }

            var photos = db.CatalogPhoto.Include(c => c.Photo).Where(c => c.CatalogId == catalogId);
            ViewBag.CatalogId = catalogId;
            return View(photos.ToList());
        }

        // GET: Photo/Add
        public ActionResult Add(int? catalogId)
        {
            // 未登录跳转
            if (Session["id"] == null)
            {
                return RedirectToAction("Login", "User");
            }

            // 判断参数
            if (catalogId == null)
            {
                return RedirectToAction("Error", "Home", new { msg = "请求参数丢失" });
            }

            ViewBag.CatalogId = catalogId;
            return View();
        }

        /*
        * @Title: Photo/Add
        * @Doc: 用户添加图片
        * @param CatalogId 目录ID
        * @param Name 图片名字
        * @param PhotoPath 图片存储路径
        * @param Introduction 图片介绍
        */
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Add([Bind(Include = "CatalogId,Name,PhotoPath,Introduction")] PhotoVO photoVO)
        {
            if (ModelState.IsValid)
            {
                // 获取图片
                HttpPostedFileBase file = Request.Files["file"];
                if(file == null)
                {
                    return RedirectToAction("Error", "Home", new { msg = "图片上传失败" });
                }
                string filePath = Path.Combine(HttpContext.Server.MapPath("/Photos"), Path.GetFileName(file.FileName));
                file.SaveAs(filePath);

                // 执行信息添加操作
                photoVO.PhotoPath = "/Photos/" + file.FileName;
                int result = db.AddPhotoToCatalog(photoVO.CatalogId, photoVO.Name, photoVO.PhotoPath, photoVO.Introduction, DateTime.Now, DateTime.Now);
                return RedirectToAction("Index", new { catalogId = photoVO.CatalogId});
            }
            return View();
        }

        // GET: Photo/Edit/5
        public ActionResult Edit(int? id)
        {
            // 未登录跳转
            if (Session["id"] == null)
            {
                return RedirectToAction("Login", "User");
            }

            // 判断参数
            if (id == null)
            {
                return RedirectToAction("Error", "Home", new { msg = "请求参数丢失" });
            }

            // 判断是否为自己的图片
            List<CatalogPhoto> catalogPhotos = db.CatalogPhoto.Where(c => c.PhotoId == id).ToList();
            if (catalogPhotos == null || catalogPhotos.Count != 1)
            {
                return RedirectToAction("Login", "User");
            }
            Catalog catalog = catalogPhotos[0].Catalog;
            List<UserCatalog> userCatalogs = db.UserCatalog.Where(u => u.CatalogId == catalog.Id).ToList();
            if (userCatalogs == null || userCatalogs.Count != 1 || userCatalogs[0].UserId != (int)Session["id"])
            {
                return RedirectToAction("Login", "User");
            }

            Photo photo = db.Photo.Find(id);

            if (photo == null)
            {
                return HttpNotFound();
            }

            return View(photo);
        }

        // POST: Photo/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,Name,PhotoPath,Introduction,UpdateTime,CreateTime")] Photo photo)
        {
            if (ModelState.IsValid)
            {
                // 数据打包
                photo.UpdateTime = DateTime.Now;

                db.Entry(photo).State = EntityState.Modified;
                db.SaveChanges();

                // 查找该记录的目录ID
                List<CatalogPhoto> catalogPhotos = db.CatalogPhoto.Where(c => c.PhotoId == photo.Id).ToList();
                if (catalogPhotos == null || catalogPhotos.Count != 1)
                {
                    return RedirectToAction("Error", "Home", new { msg = "未知错误" });
                }

                return RedirectToAction("Index", new { catalogId = catalogPhotos[0].CatalogId });
            }
            return View(photo);
        }

        // GET: Photo/Delete/5
        public ActionResult Delete(int? id)
        {
            // 未登录跳转
            if (Session["id"] == null)
            {
                return RedirectToAction("Login", "User");
            }

            // 判断参数
            if (id == null)
            {
                return RedirectToAction("Error", "Home", new { msg = "请求参数丢失" });
            }

            // 判断是否为自己的图片
            List<CatalogPhoto> catalogPhotos = db.CatalogPhoto.Where(c => c.PhotoId == id).ToList();
            if (catalogPhotos == null || catalogPhotos.Count != 1)
            {
                return RedirectToAction("Login", "User");
            }
            Catalog catalog = catalogPhotos[0].Catalog;
            List<UserCatalog> userCatalogs = db.UserCatalog.Where(u => u.CatalogId == catalog.Id).ToList();
            if (userCatalogs == null || userCatalogs.Count != 1 || userCatalogs[0].UserId != (int)Session["id"])
            {
                return RedirectToAction("Login", "User");
            }

            Photo photo = db.Photo.Find(id);

            if (photo == null)
            {
                return HttpNotFound();
            }

            return View(photo);
        }

        // POST: Photo/Delete/5
        /*
         * 1、查找图片下是否有评论
         * 2、有则无法删除
         * 3、没有可以删除，先删与catalog的关联，再删photo自身记录
         */
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            List<Comment> comments = db.Comment.Where(c => c.PhotoId == id).ToList();

            // 判断是否可删除
            if(comments == null || comments.Count != 0)
            {
                return RedirectToAction("Error", "Home", new { msg = "此图片不可删除"});
            }

            // 先删与catalog的关联
            List<CatalogPhoto> catalogPhotos = db.CatalogPhoto.Where(c => c.PhotoId == id).ToList();
            if(catalogPhotos == null || catalogPhotos.Count != 1)
            {
                return RedirectToAction("Error", "Home", new { msg = "此图片不可删除" });
            }
            db.CatalogPhoto.Remove(catalogPhotos[0]);

            // 再删photo自身记录
            Photo photo = db.Photo.Find(id);
            db.Photo.Remove(photo);

            // 执行操作
            db.SaveChanges();
            return RedirectToAction("Index", new { catalogId = catalogPhotos[0].CatalogId });
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
